import { getAchievementByDays, getLastCheckinDaysAgo } from '../../utils/util';
import { getStorage, setStorage } from '../../utils/storage';
import type { UserInfo } from '@/types/user';
import Message from 'tdesign-miniprogram/message/index';

Page({
  data: {
    userInfo: {
      nickName: '未授权用户',
      avatarUrl: 'https://via.placeholder.com/80',
      isAlive: true,
      firstCheckinDate: new Date(),
      lastCheckinDate: new Date(),
      daysAlive: 0,
      quote: '',
    } as UserInfo,
    aliveText: '我还活着',
    achievements: '',
    daysToDeath: 3,

    moodList: [
      { id: 'happy', emoji: '😄', label: '开心', color: 'yellow' },
      { id: 'sad', emoji: '😢', label: '难过', color: 'blue' },
      { id: 'tired', emoji: '😩', label: '疲惫', color: 'red' },
      { id: 'excited', emoji: '🤩', label: '兴奋', color: 'orange' },
      { id: 'calm', emoji: '😌', label: '平静', color: 'green' },
      { id: 'angry', emoji: '😠', label: '生气', color: 'red' },
      { id: 'love', emoji: '😍', label: '甜蜜', color: 'pink' },
      { id: 'confused', emoji: '😕', label: '迷茫', color: 'purple' },
      { id: 'relaxed', emoji: '😎', label: '放松', color: 'cyan' },
    ],
    selectedMood: '',
    selectedMoodLabel: '',

    motivationalQuotes: [
      '今天也是充满希望的一天！🌞',
      '坚持不懈，才能看到彩虹。🌈',
      '心情美好，世界就美好。✨',
      '每一步都算数，别轻易放弃。🚶‍♂️',
      '给自己一个微笑，迎接新挑战。😊',
    ],
    randomQuoteIndex: 0,

    loading: false,
    userQuote: '',
    isPressed: false,
  },

  onLoad() {
    const app = getApp<IAppOption>();
    const cachedUser = getStorage<UserInfo>('userInfo');

    if (cachedUser) {
      const updatedUser = this.processUserInfo(cachedUser);
      this.setData({
        userInfo: updatedUser,
        achievements: getAchievementByDays(updatedUser.daysAlive),
        daysToDeath: updatedUser.daysToDeath,
      });
    }

    const savedMood = wx.getStorageSync('todayMood') || '';
    const mood = this.data.moodList.find(m => m.id === savedMood);
    this.setData({
      selectedMood: savedMood,
      selectedMoodLabel: mood ? mood.label : '',
      randomQuoteIndex: Math.floor(Math.random() * this.data.motivationalQuotes.length),
    });

    if (app.globalData.userId) {
      this.loadUserFromDB(app.globalData.userId);
    } else {
      app.openidReadyCallback = (openid: string) => {
        this.loadUserFromDB(openid);
      };
    }
  },

  async loadUserFromDB(openid: string) {
    try {
      const res = await wx.cloud.callFunction({
        name: 'user_operate',
        data: {
          action: 'getUser',
          openid,
        },
      });

      if (res.result.success && res.result.user) {
        const dbUser = res.result.user;
        const updatedUser = this.processUserInfo(dbUser);
        setStorage('userInfo', updatedUser);
        this.setData({
          userInfo: updatedUser,
          achievements: getAchievementByDays(updatedUser.daysAlive),
          daysToDeath: updatedUser.daysToDeath,
        });
      } else {
        console.warn('云函数未返回用户信息，使用默认值');
      }
    } catch (err) {
      console.error('调用 user_operate 获取用户失败：', err);
    }
  },

  processUserInfo(user: UserInfo) {
    const now = new Date();
    const lastDate = new Date(user.lastCheckinDate);

    const daysSinceLastCheckin = Math.floor(
      (now.getTime() - lastDate.getTime()) / (1000 * 60 * 60 * 24)
    );
    const DEAD_THRESHOLD = 3;

    const isAlive = daysSinceLastCheckin < DEAD_THRESHOLD;
    const totalAliveDays = isAlive ? user.daysAlive + daysSinceLastCheckin : user.daysAlive;
    const daysToDeath = Math.max(DEAD_THRESHOLD - daysSinceLastCheckin, 0);

    const lastCheckin = getLastCheckinDaysAgo(lastDate);
    const aliveText = isAlive ? '我还活着' : '立即复活';

    this.setData({ aliveText });

    return {
      ...user,
      isAlive,
      daysAlive: totalAliveDays,
      lastCheckinDate: lastDate,
      lastCheckin,
      daysToDeath,
    };
  },

  onMoodSelect(e: WechatMiniprogram.TouchEvent) {
    const id = e.currentTarget.dataset.id;
    const mood = this.data.moodList.find((m) => m.id === id);

    if (!mood) return;

    this.setData({
      selectedMood: id,
      selectedMoodLabel: mood.label,
    });

    wx.setStorageSync('todayMood', id);
  },

  async onAliveTap() {
    try {
      // 获取用户资料
      const userProfile = await wx.getUserProfile({ desc: '完善用户资料' });
      const app = getApp<IAppOption>();
      const openid = app.globalData.userId;
      if (!openid) throw new Error('未获取到用户openid');

      const moodLabel = this.data.selectedMoodLabel;
      const content = moodLabel
        ? `知道了，您还活着 🌱，已记录今日心情：${moodLabel}`
        : '知道了，您还活着 🌱';

      Message.info({
        context: this,
        offset: [20, 32],
        duration: 2200,
        content,
      });

  
      // 先调用打卡更新云函数
      const res = await wx.cloud.callFunction({
        name: 'checkin_with_user_update',
        data: {
          openid,
          userInfo: {
            nickName: userProfile.userInfo.nickName,
            avatarUrl: userProfile.userInfo.avatarUrl,
          },
        },
      });
  
      if (!res.result.success) {
        return;
      }
      
  
      // 处理更新后的用户信息
      const updatedUser: UserInfo = res.result.userInfo;
      const processedUser = this.processUserInfo(updatedUser);
      setStorage('userInfo', processedUser);
  
      this.setData({
        userInfo: processedUser,
        achievements: getAchievementByDays(processedUser.daysAlive),
        daysToDeath: processedUser.daysToDeath,
      });
  
      // 如果选中了心情，保存心情记录到新表
      if (this.data.selectedMood) {
        const moodRes = await wx.cloud.callFunction({
          name: 'mood_record_operate',
          data: {
            action: 'saveMood',
            openid,
            moodId: this.data.selectedMood,
            timestamp: Date.now(),
          },
        });
  
        if (!moodRes.result.success) {
          console.warn('保存心情记录失败', moodRes);
        }
      }
    } catch (err) {
      console.error('打卡失败', err);
    }
  },

  handlePressStart() {
    this.setData({ isPressed: true });
  },

  handlePressEnd() {
    this.setData({ isPressed: false });
  },
  
});
